﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.Utils;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PR_BudgetManage : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private BudgetManagementTestBLL BLL = new BudgetManagementTestBLL();
        private IEmployeeTypeBLL etBLL = new EmployeeTypeBLL();

        double sum = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
	        if (!IsPostBack)
	        {
		        bindEmpType();
		        bindYearCombo();
		        LoadDataGrid();
	        } 
        }

	    private enum Mode
	    {
		    Viewing,
		    Editing
	    };

	    private void GuiBehavierChange(Mode mode)
		{ 
			var cmdInsertSelect = FindControlRecursive(RadGrid1, "cmdInsertSelect") as LinkButton;
			var cmdEdit = FindControlRecursive(RadGrid1, "cmdEdit") as LinkButton;
			var cmdCancel = FindControlRecursive(RadGrid1, "cmdCancel") as LinkButton;
			cmdEdit.Visible = mode == Mode.Viewing;
			cmdInsertSelect.Visible = mode == Mode.Editing;
			cmdCancel.Visible = mode == Mode.Editing; 
		}

		public static Control FindControlRecursive(Control root, string id)
		{
			return (root.ID == id) ? root : (from Control ctl in root.Controls select FindControlRecursive(ctl, id)).FirstOrDefault(foundCtl => foundCtl != null);
		}

	    private void LoadDataGrid()
        {            
            try
            {
                int nYear = cmbFilterYear.SelectedValue.Length > 0 ? Int32.Parse(cmbFilterYear.SelectedValue) : 0;
                int nPromotion = radPromotion.SelectedValue.Length > 0 ? Int32.Parse(radPromotion.SelectedValue) : 0;
                int nEmpType = cmbEmployeeType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmployeeType.SelectedValue) : 0;

                DataTable jobsite = BLL.Management(nYear, nPromotion, nEmpType);
                RadGrid1.DataSource = jobsite;
                RadGrid1.DataBind();

                SumFooter();
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this, ex.Message);
            }
        }
        private void bindEmpType()
        {
            IList<EmployeeTypeInfo> infoList = etBLL.ListEmployeeTypes();

            cmbEmployeeType.DataSource = infoList;
            cmbEmployeeType.DataBind();
            cmbEmployeeType.SelectedIndex = 0;
        }
        public void bindYearCombo()
        {
            int curYear = int.Parse(DateTime.Today.Year.ToString());
            curYear += 543;
            int MinYear = curYear - 10;
            int MaxYear = curYear + 10;
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("Name");

            for (int i = MinYear; i <= MaxYear; i++)
            {
                dt.Rows.Add(Convert.ToString(i));
            }
            cmbFilterYear.DataSource = dt;
            cmbFilterYear.DataBind();
            cmbFilterYear.SelectedValue = curYear.ToString();
            cmbYear_SelectedIndexChanged(null, null);
        }
        private void SumFooter()
        {
            GridItem[] gridItem = RadGrid1.MasterTableView.GetItems(GridItemType.Footer);
            RadNumericTextBox txtSumAmount = (RadNumericTextBox)gridItem[0].FindControl("txtSumAmount");
            RadNumericTextBox txtSumAmountNet = (RadNumericTextBox)gridItem[0].FindControl("txtSumAmountNet");
            double dSumAmount = 0;
            double dSumAmountNet = 0;

            for (int i = 0; i < RadGrid1.Items.Count; i++ )
            {
                RadNumericTextBox txtAmount = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtAmount");
                RadNumericTextBox txtAmountNet = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtAmountNet");
                string strAmount = txtAmount.Text;
                string strAmountNet = txtAmountNet.Text;

                dSumAmount += (strAmount.Length > 0 ? Convert.ToDouble(strAmount) : 0);
                dSumAmountNet += (strAmountNet.Length > 0 ? Convert.ToDouble(strAmountNet) : 0);
            }

            txtSumAmount.Text = dSumAmount.ToString();
            txtSumAmountNet.Text = dSumAmountNet.ToString();
        }
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                //RadNumericTextBox txtSumSalary = (RadNumericTextBox)dataItem["sum_salary_template"].FindControl("txtSumSalary");
                //Label lblSumSalary = (Label)dataItem["sum_salary_template"].FindControl("lblSumSalary");
                RadNumericTextBox txtSumSalary = (RadNumericTextBox)dataItem["sum_salary_template"].FindControl("txtSumSalary");
                RadNumericTextBox txtBudgetPercent = (RadNumericTextBox)dataItem["Template1"].FindControl("txtBudgetPercent");
                RadNumericTextBox txtAmount = (RadNumericTextBox)dataItem["amount"].FindControl("txtAmount");
                //RadNumericTextBox txtSumAmount = (RadNumericTextBox)dataItem["amount"].FindControl("txtSumAmount");
                RadNumericTextBox txtAmountNet = (RadNumericTextBox)dataItem["amount_net"].FindControl("txtAmountNet");
                //RadNumericTextBox txtSumAmountNet = (RadNumericTextBox)dataItem["amount_net"].FindControl("txtSumAmountNet");

                txtBudgetPercent.Attributes.Add("OnBlur", string.Format("Blur('{0}', '{1}', '{2}', '{3}')"
                    , txtSumSalary.ClientID, txtBudgetPercent.ClientID, txtAmount.ClientID, ""));
                txtBudgetPercent.Attributes.Add("OnFocus", string.Format("Focus('{0}', '{1}', '{2}', '{3}')"
                    , txtSumSalary.ClientID, txtBudgetPercent.ClientID, txtAmount.ClientID, ""));
                txtAmountNet.Attributes.Add("OnBlur", string.Format("NetBlur('{0}', '{1}')"
                    , txtAmountNet.ClientID, ""));
                txtAmountNet.Attributes.Add("OnFocus", string.Format("NetFocus('{0}', '{1}')"
                    , txtAmountNet.ClientID, ""));

                //string strBathAmount = txtBathAmount.Text;
                //if (strBathAmount.Length == 0)
                //    strBathAmount = "0";
                //sum += double.Parse(strBathAmount);
            }

            //if (e.Item is GridDataItem)
            //{
            //    GridDataItem dataItem = (GridDataItem)e.Item;
            //    sum += double.Parse((dataItem["Template1"].FindControl("TextBox1") as RadNumericTextBox).Value.ToString());
            //}
            //else if (e.Item is GridFooterItem)
            //{
            //    GridFooterItem footer = (GridFooterItem)e.Item;
            //    footer["job_site_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>Total freight on this page is:</span> "));
            //    (footer["Template1"].FindControl("TextBox2") as RadNumericTextBox).Value = Double.Parse(sum.ToString());
            //}
        }
        protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Delete")
				{
					GuiBehavierChange(Mode.Viewing);
                }
                else if (e.CommandName == "btnClick")
				{
					GuiBehavierChange(Mode.Viewing);
                    return;
                }
                else if (e.CommandName == "CancelView")// คลิกยกเลิก
				{
					GuiBehavierChange(Mode.Viewing);
                    e.Canceled = true;
                }
                else if (e.CommandName == "EditView")// คลิกแก้ไข
				{
					GuiBehavierChange(Mode.Editing);
                    GridDataItem item;

                    for (int i = 0; i < RadGrid1.Items.Count; i++)
                    {
                        item = RadGrid1.Items[i];

                        RadNumericTextBox txtSumSalary = (RadNumericTextBox)item["sum_salary"].FindControl("txtSumSalary");
                        RadNumericTextBox txtBudgetPercent = (RadNumericTextBox)item["Template1"].FindControl("txtBudgetPercent");
                        RadNumericTextBox txtAmount = (RadNumericTextBox)item["amount"].FindControl("txtAmount");
                        RadNumericTextBox txtAmountNet = (RadNumericTextBox)item["amount_net"].FindControl("txtAmountNet");

                        Label lblSumSalary = (Label)item["sum_salary"].FindControl("lblSumSalary");
                        Label lblBudgetPercent = (Label)item["Template1"].FindControl("lblBudgetPercent");
                        Label lblAmount = (Label)item["amount"].FindControl("lblAmount");
                        Label lblAmountNet = (Label)item["amount_net"].FindControl("lblAmountNet");

                        txtSumSalary.Visible = true;
                        txtBudgetPercent.Visible = true;
                        txtAmount.Visible = true;
                        txtAmountNet.Visible = true;

                        lblSumSalary.Visible = false;
                        lblBudgetPercent.Visible = false;
                        lblAmount.Visible = false;
                        lblAmountNet.Visible = false;
                    }

                    return;
                }
                else if (e.CommandName == "InsertSelect")// Auto Insert
                {
                    GridDataItem item;

                    for (int i = 0; i < RadGrid1.Items.Count; i++)
                    {
                        item = RadGrid1.Items[i];

                        RadNumericTextBox txtBudgetPercent = (RadNumericTextBox)item["Template1"].FindControl("txtBudgetPercent");
                        RadNumericTextBox txtAmount = (RadNumericTextBox)item["amount"].FindControl("txtAmount");
                        RadNumericTextBox txtAmountNet = (RadNumericTextBox)item["amount_net"].FindControl("txtAmountNet");
                        Label lblJobSiteSeq = (Label)item["job_site_seq"].FindControl("lblJobSiteSeq");

                        string strPK = item.OwnerTableView.DataKeyValues[i]["mng_seq"].ToString();
                        double BudgetPercent = txtBudgetPercent.Text.Length > 0 ? double.Parse(txtBudgetPercent.Text) : 0;
                        double Amount = txtAmount.Text.Length > 0 ? double.Parse(txtAmount.Text) : 0;
                        double AmountNet = txtAmountNet.Text.Length > 0 ? double.Parse(txtAmountNet.Text) : 0;

                        if (strPK.Length <= 0)
                        { 
                            int PrmSeq = BLL.GetPrmPromotionSeq(Int32.Parse(cmbEmployeeType.SelectedValue)
                                , Int32.Parse(cmbFilterYear.SelectedValue)
                                , Int32.Parse(radPromotion.SelectedValue));

                            BLL.InsertManagement(PrmSeq
                                , Int32.Parse(lblJobSiteSeq.Text)
                                , BudgetPercent
                                , Amount
                                , AmountNet
                                , ssMng.EmpSeqI);

                            strPK = BLL.GetManageSeq(Int32.Parse(lblJobSiteSeq.Text), PrmSeq).ToString();
                        }

                        BLL.UpdateManagement(Int32.Parse(strPK.Length > 0 ? strPK : "0")
                               , BudgetPercent, Amount, AmountNet
                               , ssMng.EmpSeqI);
                    }

                }

                LoadDataGrid();
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this, ex.Message);
            }
        }
        protected void cmbYear_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }

        protected void radPromotion_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataGrid();
        }
        protected void cbEmployeeType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }
    }
}